<script setup lang="ts">
import { watchEffect } from 'vue';
import { ThemeEnum } from '@/types/global.d';
import { SystemConstant } from '@/constants/SystemConstant.ts';
import { useSystemStore } from '@/stores/systemStore.ts';

// ———————————————————————————————————————————————— 主题功能 ——————————————————————————————————————————————
const match = matchMedia(`(prefers-color-scheme: ${ThemeEnum.DARK})`); // 媒体查询
const systemStore = useSystemStore();
/**
 * 跟随系统的主题切换
 */
const followOS = () => {
    if (match.matches) {
        // 如果是黑色主题
        document.documentElement.dataset.theme = ThemeEnum.DARK;
    } else {
        document.documentElement.dataset.theme = ThemeEnum.LIGHT; // 亮色主题
    }
};

watchEffect(() => {
    localStorage.setItem(SystemConstant.THEME, systemStore.currentTheme);
    if (systemStore.currentTheme === ThemeEnum.AUTO) {
        //跟随系统
        followOS();
        match.addEventListener('change', followOS);
    } else {
        match.removeEventListener('change', followOS);
        document.documentElement.dataset.theme = systemStore.currentTheme;
    }
});
// ——————————————————————————————————————————————————————————————————————————————————————————————————
</script>
<template>
    <RouterView />
</template>
